package com.rabbitmq.demo.pull_manual;


import com.rabbitmq.client.Channel;
import com.rabbitmq.client.GetResponse;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@Slf4j
@RestController
public class ReceiverPull {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping(value="/receive")
    public void receive(){
        long deliveryTag = 0;
        Channel channel = rabbitTemplate.getConnectionFactory().createConnection().createChannel(false);
        try {
            GetResponse response = channel.basicGet("queue", false);
            deliveryTag = response.getEnvelope().getDeliveryTag();
            byte[] body = response.getBody();
            log.info("pull message is :{}",new String(body));
            channel.basicAck(deliveryTag,false);
            // 拒绝消费消息
            // channel.basicReject(deliveryTag,false);
        } catch (IOException e) {
            try {
                channel.basicNack(deliveryTag,false,true);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            e.printStackTrace();
        }
    }
}
